package com.awen.sqlSession;
import com.awen.config.BoundSql;
import com.awen.pojo.Configuration;
import com.awen.pojo.MappedStatement;
import com.awen.utils.GenericTokenParser;
import com.awen.utils.ParameterMapping;
import com.awen.utils.ParameterMappingTokenHandler;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class SimpleExecutor implements Executor {
    @Override
    public <E> List<E> query(Configuration configuration, MappedStatement mappedStatement, Object... params) throws SQLException, NoSuchFieldException, IllegalAccessException, InstantiationException, IntrospectionException, InvocationTargetException {
        PreparedStatement preparedStatement = common(configuration, mappedStatement, params[0]);
        ResultSet resultSet = preparedStatement.executeQuery();
        //封装返回结果集
        String resultType = mappedStatement.getResultType();
        Class<?> resultTypeclass = getClassType(resultType);
        ArrayList<Object> arrayList = new ArrayList<>();
        while(resultSet.next()){
            //元数据
            ResultSetMetaData metaData = resultSet.getMetaData();
            Object newInstance = resultTypeclass.newInstance();
            for (int i = 1; i <= metaData.getColumnCount() ; i++) {
                //字段名
                String columnName = metaData.getColumnName(i);
                Object value = resultSet.getObject(columnName);
                //使用反射或者内省，根据数据库表和实体的对应关系，完成封装
                PropertyDescriptor propertyDescriptor = new PropertyDescriptor(columnName, resultTypeclass);
                Method writeMethod = propertyDescriptor.getWriteMethod();
                writeMethod.invoke(newInstance,value);
            }
            arrayList.add(newInstance);
        }
        return (List<E>) arrayList;
    }

    @Override
    public Integer update(Configuration configuration, MappedStatement mappedStatement, Object... params) throws Exception {
        PreparedStatement preparedStatement = common(configuration, mappedStatement, params[0]);
        Integer update = preparedStatement.executeUpdate();
        return update;
    }

    private Class<?> getClassType(String classname) {
        if(classname != null){
            Class<?> aClass = null;
            try {
                aClass = Class.forName(classname);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
            return aClass;
        }
        return null;
    }
//    //获取连接
//    private ResultSet getResultSet(Configuration configuration, MappedStatement mappedStatement, Object param) throws SQLException, NoSuchFieldException, IllegalAccessException {
//        PreparedStatement preparedStatement = common(configuration, mappedStatement, param);
//        //执行sql
//        return preparedStatement.executeQuery();
//    }

    private PreparedStatement common(Configuration configuration, MappedStatement mappedStatement, Object param) throws SQLException, NoSuchFieldException, IllegalAccessException {
        //1.注册驱动，获取连接
        Connection connection = configuration.getDataSource().getConnection();
        //2.获取sql语句
        String sql = mappedStatement.getSql();
        BoundSql boundSql = getBoundSql(sql);
        //获取预处理对象:prepareStatement
        PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSqlText());
        //设置参数
        String paramterType = mappedStatement.getParamterType();
        Class<?> paramterTypeclass = getClassType(paramterType);
        List<ParameterMapping> list = boundSql.getList();
        for (int i = 0; i < list.size(); i++) {
            String content = list.get(i).getContent();
            //反射
            Field declaredField = paramterTypeclass.getDeclaredField(content);
            //打破封装
            declaredField.setAccessible(true);
            Object o = declaredField.get(param);
            preparedStatement.setObject(i + 1,o);
        }
        return preparedStatement;
    }

    /**
     * 完成对#{}的解析工作：1.将#{}使用？进行代替。2.解析出#{}里面的值进行存储
     * @param sql
     * @return
     */
    private BoundSql getBoundSql(String sql){
        //标记处理类：配合标记解析器来完成对占位符的解析处理工作
        ParameterMappingTokenHandler tokenHandler = new ParameterMappingTokenHandler();
        GenericTokenParser tokenParser = new GenericTokenParser("#{","}", tokenHandler);
        //解析出来的sql
        String parseSql = tokenParser.parse(sql);
        //#{}里面解析出来的参数名称
        List<ParameterMapping> parameterMappings = tokenHandler.getParameterMappings();
        BoundSql boundSql = new BoundSql(parseSql,parameterMappings);
        return boundSql;
    }
}
